package com.knowif.backend.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.PageInfo;
import com.knowif.backend.dto.TutorPublishDto;
import com.knowif.dao.*;
import com.knowif.enumInfo.EducationTypeEnum;
import com.knowif.pojo.*;
import com.knowif.search.Sort;
import com.knowif.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.knowif.enumInfo.InfoStatusEnum;
import com.knowif.search.SearchCondition;
import com.knowif.system.model.RestBean;
import com.knowif.util.ExampleUtil;
import com.knowif.util.commonUtil.StringUtil;

@Service
public class TutorService {

	@Autowired
	private Fuzzy_service fuzzy_service;
	@Autowired
	private Tutor_service tutor_service;
	@Autowired
	private UserItem_service userItem_service;
	@Autowired
	private UserCollect_service userCollect_service;
	@Autowired
	private School_service school_service;
	@Autowired
	private Special_service special_service;
	@Autowired
	private UserItemMapper userItemMapper;
	@Autowired
	private TutorEducationInfo_service tutorEducationInfo_service;
	@Autowired
	private TutorInfoMapper tutorInfoMapper;
	@Autowired
	private TUserMapper tUserMapper;
	@Autowired
	private TutorEducationInfoMapper tutorEducationInfoMapper;
	@Autowired
	private FuzzySearchMapper fuzzySearchMapper;

	/**
	 * @author: xingyao
	 * @Description: 模糊查询功能
	 * @param searchCondition
	 * @return
	 * @throws Exception
	 */
	public RestBean<?> fuzzySearch(SearchCondition searchCondition) throws Exception {
		if (searchCondition == null) {
			return RestBean.buildError("请输入查询内容");
		}
		FuzzySearchExample fuzzySearchExample = ExampleUtil.buildExample(new FuzzySearchExample(), searchCondition);
		Object obj = searchCondition.getContitionValue("searchContent");
		if (obj instanceof String || obj instanceof Integer) {
			String fuzzyContext = obj + "";
			return fuzzy_service.fuzzySearchTutor(fuzzySearchExample, fuzzyContext);
		} else {
			return RestBean.buildError("格式不正确");
		}
	}


	/**
	 * @author: xingyao
	 * @Description: 默认排序功能实现
	 * @return
	 * @throws Exception
	 */
	public RestBean<?> selectOrderByHelpNum(SearchCondition searchCondition) throws Exception {
		List<Integer> tutorIds = new ArrayList<Integer>();
		if(searchCondition != null){
			int itemId = (int) searchCondition.getContitionValue("itemId");
			UserItemExample userItemExample = new UserItemExample();
			userItemExample.createCriteria().andItemIdEqualTo(itemId);
			List<UserItem> userItems = userItem_service.selectUserItem(userItemExample);
			tutorIds = UserItem.getTutorIds(userItems);
		}
		TutorInfoExample tutorInfoExample = ExampleUtil.buildExample(new TutorInfoExample(), searchCondition);
		if(tutorIds != null && !tutorIds.isEmpty()){
			tutorInfoExample.createCriteria().andIdIn(tutorIds);
		}
		tutorInfoExample.setOrderByClause("helpsNum");
		RestBean<?> restBean = RestBean.buildSuccess(tutor_service.selectTutor(tutorInfoExample));
		return restBean;
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  通过分数进行排序
	 * @param searchCondition
	 * @return
	 * @throws Exception
	 */
	public RestBean<?> selectOrderBytotalScore( SearchCondition searchCondition) throws Exception{
		List<Integer> tutorIds = new ArrayList<Integer>();
		if(searchCondition != null){
			int itemId = (int) searchCondition.getContitionValue("itemId");
			UserItemExample userItemExample = new UserItemExample();
			userItemExample.createCriteria().andItemIdEqualTo(itemId);
			List<UserItem> userItems = userItem_service.selectUserItem(userItemExample);
			tutorIds = UserItem.getTutorIds(userItems);
		}
		TutorInfoExample tutorInfoExample = ExampleUtil.buildExample(new TutorInfoExample(), searchCondition);
		if(tutorIds != null && !tutorIds.isEmpty()){
			tutorInfoExample.createCriteria().andIdIn(tutorIds);
		}
		tutorInfoExample.setOrderByClause("totalScore");
		RestBean<?> restBean = RestBean.buildSuccess(tutor_service.selectTutor(tutorInfoExample));
		return restBean;
	}

	/**
	 * @author: xingyao
	 * @Description: 通过城市名称、学院名称、学校所在城市进行导师信息查找
	 * @param searchCondition
	 * @return
	 */
	public RestBean<?> selectByCondition(SearchCondition searchCondition) {
		if (searchCondition == null) {
			return RestBean.buildError("请输入查询条件");
		}
		String city = (String) searchCondition.getContitionValue("city");
		String college = (String) searchCondition.getContitionValue("college");
		String school_city = (String) searchCondition.getContitionValue("school_city");
		int itemId = (int) searchCondition.getContitionValue("itemId");
		if (StringUtil.isEmpty(city) && StringUtil.isEmpty(college) && StringUtil.isEmpty(school_city)) {
			return RestBean.buildError("请输入查询条件");
		}
		return tutor_service.selectByCondition(itemId,city, college, school_city);
	}

	
	
	/**
	 * @author: xingyao 
	 * @Description:  分类查找导师信息
	 * @param searchCondition
	 * @return
	 * @throws Exception
	 */
	public RestBean<?> selectTutorByItem(SearchCondition searchCondition) throws Exception{
		if(searchCondition == null){
			return RestBean.buildError("请输入要查找的分类id");
		}
		UserItemExample userItemExample = ExampleUtil.buildExample(new UserItemExample(), searchCondition);
		return tutor_service.selectTutorByItem(userItemExample);
	}
	
	
	/**
	 * @author: xingyao 
	 * @Description:  得到导师信息详情功能
	 * @param tutorId
	 * @param userId
	 * @return
	 */
	public RestBean<?> selectTutorInfo(Integer tutorId,Integer userId){
		if(tutorId == null){
			return RestBean.buildError("请输入要查看的导师id");
		}
		if(userId == null){
			return RestBean.buildError("请输入用户id",RestBean.NOTUSERID);
		}
		TutorInfo tutorInfo = tutor_service.selectByTutorId(tutorId);
		//在拿出来该用户是否被收藏了
		if(userId != null){
			boolean boo = userCollect_service.isBeCollect(userId, tutorId);
			if(boo){
				tutorInfo.setIsBeCollect(InfoStatusEnum.ISBECOLLECT.getStatus());
			}else{
				tutorInfo.setIsBeCollect(InfoStatusEnum.ISNOTBECOLLECT.getStatus());
			}
		}
		return RestBean.buildSuccess(tutorInfo);
	}

	/**
	 * 更新导师信息
	 * @param tutorInfo
	 * @return
	 */
	public RestBean<?> update(TutorInfo tutorInfo) {
		tutor_service.updateTutorNotNull(tutorInfo);
		return RestBean.buildSuccess("更新成功");
	}

	/**
	 * 导师筛选
	 * @param searchCondition
	 */
	public PageInfo<TutorInfo> screen(SearchCondition searchCondition) {
		Map<String, Object> params = searchCondition.getParameterMap();
		Sort sort = searchCondition.getSort();
		if(sort != null && !StringUtil.isEmpty(sort.getField())){
			params.put("sort", sort.getField());
		}
		return tutor_service.screen(params, searchCondition.getPageSize(), searchCondition.getPageNumber());
	}

	/**
	 * 通过用户id查询导师信息
	 * @param userId
	 * @return
	 */
	public RestBean<?> selectTutorInfoByUserId(Integer userId) {
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(userId);
		List<TutorInfo> tutorInfos = tutor_service.selectTutor(tutorInfoExample);
		if(tutorInfos == null || tutorInfos.size() == 0){
			return RestBean.buildError("该用户导师信息不存在");
		}else{
			return RestBean.buildSuccess(tutorInfos.get(0));
		}
	}

	/**
	 * 自我发布
	 * @param tutorPublishDto
	 * @return
	 */
    public RestBean selfPublish(TutorPublishDto tutorPublishDto) {
		// 通过userId查找tutorInfo，如果存在，则不需要执行插入操作
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(tutorPublishDto.getUserId());
		List<TutorInfo> tutorInfos = tutorInfoMapper.selectByExample(tutorInfoExample);
		if (tutorInfos != null && !tutorInfos.isEmpty()) {
			return RestBean.buildError("该名用户已经是导师了");
		}
		TutorInfo tutorInfo = new TutorInfo();
		tutorInfo.setDescrition_NotFileter(tutorPublishDto.getSelfShow());
		int userId = tutorPublishDto.getUserId();
		//1国内2国外
		int schoolType = tutorPublishDto.getSchoolType();
		int eductionType = tutorPublishDto.getEductionType();
		String specialName = tutorPublishDto.getSpecialName();

		String schoolName = tutorPublishDto.getSchoolName();
		SchoolExample schoolExample = new SchoolExample();
		schoolExample.createCriteria().andSchoolNameEqualTo(schoolName);
		List<School> schools = school_service.selectSchool(schoolExample);

		TutorEducationInfo tutorEducationInfo = new TutorEducationInfo();
		tutorEducationInfo.setEduLevelId(tutorPublishDto.getEductionType());
		tutorEducationInfo.setEduLevelName(EducationTypeEnum.getEducationTypes().get(tutorPublishDto.getEductionType()));

		/** 导师类目 **/
		UserItem userItem = new UserItem();
			userItem.setUserId(userId);
		if(schoolType == 1){
			if(eductionType == 1){
				userItem.setItemId(4);
			}else{
				userItem.setItemId(1);
			}
		}else if (schoolType == 2){
			userItem.setItemId(2);
		}
		userItemMapper.insert(userItem);
		tutorEducationInfo.setUserItemId(userItem.getId());

		if(schools.isEmpty()){
			School school = new School();
			school.setSchoolId(school_service.selectMaxSchoolId() + 1);
			school.setSchoolName(schoolName);
			int schoolId = school_service.saveSchool(school);
			Special special = new Special();
			special.setSchoolId(schoolId);
			special.setSpecialName(specialName);
			int specialId = special_service.saveSpecial(special);
			tutorEducationInfo.setSchoolId(schoolId);
			tutorEducationInfo.setSchoolName(schoolName);
			tutorEducationInfo.setSpecialId(specialId);
			tutorEducationInfo.setSpecialName(specialName);
		}else{
			School school = schools.get(0);
			tutorEducationInfo.setSchoolId(school.getId());
			tutorEducationInfo.setSchoolName(schoolName);
			tutorEducationInfo.setProvinceId(school.getProvinceId());
			tutorEducationInfo.setContinentId(school.getContinentId());
			tutorEducationInfo.setCountryId(school.getCountryId());
			SpecialExample specialExample = new SpecialExample();
			specialExample.createCriteria().andSchoolIdEqualTo(school.getSchoolId())
					.andSpecialNameEqualTo(specialName);
			List<Special> specials = special_service.selectSpecial(specialExample);
			if(specials.isEmpty()){
				Special special = new Special();
				special.setSchoolId(school.getSchoolId());
				special.setSpecialName(specialName);
				int specialId = special_service.saveSpecial(special);
				tutorEducationInfo.setSpecialId(specialId);
				tutorEducationInfo.setSpecialName(specialName);
			}else{
				tutorEducationInfo.setSpecialId(specials.get(0).getId());
				tutorEducationInfo.setSpecialName(specialName);
			}
		}

		tutorInfo.setUserId(userId);
		//首页查询为推荐位
		tutorInfo.setIsTj(1);
		tutorInfo.setTutorEducationInfo(tutorEducationInfo);

		userItem.setTutorEducationInfo(tutorEducationInfo);
		List<UserItem> userItems = new ArrayList<>();
		userItems.add(userItem);
		tutorInfo.setUserItem(userItems);
		return tutor_service.saveSelfPublishTutor(tutorInfo, tutorPublishDto.getContact());
    }

	/**
	 * 修改名
	 * @param userId
	 * @param fullName
	 * @return
	 */
	public RestBean updateFullName(int userId, String fullName) {
		if(StringUtil.isEmpty(fullName)){
			return RestBean.buildError("fullName不能为空");
		}
		TUser tUser = new TUser();
		tUser.setFullName(fullName);

		//添加到模糊查询
		FuzzySearchExample fuzzySearchExample = new FuzzySearchExample();
		fuzzySearchExample.createCriteria().andUserIdEqualTo(userId).andSearchNameEqualTo("fullName");
		fuzzySearchMapper.deleteByExample(fuzzySearchExample);

		FuzzySearch fuzzySearch = new FuzzySearch();
		fuzzySearch.setUserId(userId);
		fuzzySearch.setSearchName("fullName");
		fuzzySearch.setSearchContent(fullName);
		fuzzySearchMapper.insert(fuzzySearch);

		TUserExample tUserExample = new TUserExample();
		tUserExample.createCriteria().andIdEqualTo(userId);
		tUserMapper.updateByExampleSelective(tUser, tUserExample);
		return RestBean.buildSuccess("修改成功");
	}

	/**
	 * 修改分享
	 * @param userId
	 * @param selfShow
	 * @return
	 */
	public RestBean updateSelfShow(int userId, String selfShow) {
		if(StringUtil.isEmpty(selfShow)){
			return RestBean.buildError("selfShow不能为空");
		}
		TutorInfo tutorInfo = new TutorInfo();
		tutorInfo.setSelfShow(selfShow);
		TutorInfoExample tutorInfoExample = new TutorInfoExample();
		tutorInfoExample.createCriteria().andUserIdEqualTo(userId);
		tutorInfoMapper.updateByExampleSelective(tutorInfo, tutorInfoExample);
		return RestBean.buildSuccess("修改成功");
	}
}














